<?php
/**
 * Created by PhpStorm.
 * Script Name: AppInit.php
 * Create: 2022/9/19 19:15
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\wap\middleware;

use app\common\service\App;
use plugin\wechat\app\service\MpFollow as FollowService;
use plugin\wechat\app\service\Mp as MpService;
use support\View;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AppInit implements MiddlewareInterface
{
    /**
     * @inheritDoc
     */
    public function process(Request $request, callable $handler): Response
    {
        $app        = request()->getApp();
        $controller = strtolower(request()->getController());
        $action     = request()->getAction();

        $controller_layer = explode('/', $controller);
        $controller = $controller_layer[count($controller_layer) - 1];
        $request->controller = $controller;
        $request->appInfo = App::getApp($request->plugin);
        $request->appId = input('appid', '');
        if(is_string($request = self::setMpInfo($request))){
            return  error($request);
        }
        $request = self::setApp($request);

        if(is_string($request = self::setTenantId($request))){
            return  error($request);
        }

        if(is_string($request = self::setFollowInfo($request))){
            return redirect($request);
        }
        return $handler($request);
    }

    /**
     * 设置微信公众号
     * @param $request
     * @return
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author fudaoji<fdj@kuryun.cn>
     */
    static function setMpInfo(Request $request) {
        if($request->appId){
            $request->mpInfo = MpService::getInfo($request->appId);
        }else{
            $request->mpInfo = session(WECHAT_WAP_MP, '');
        }
        if($request->mpInfo){
            session([WECHAT_WAP_MP => $request->mpInfo]);
            View::assign('mp_info', $request->mpInfo);
            return $request;
        }
        return  "公众号不存在";
    }

    /**
     * 设置授权公众号
     * @param Request $request
     * @return Request|string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    protected function setApp(Request $request) {
        $request->mpApp = MpService::getApp($request->mpInfo, $request);
        return $request;
    }

    static function setFollowInfo(Request &$request){
        if(in_array($request->controller, ['index'])){
            $mp_info = $request->mpInfo;

            $follow_info = session(SESSION_MP_FOLLOW);
            if(empty($follow_info) && $openid = input('openid', '')){
                $follow_info = FollowService::getFollowInfo($openid, $mp_info);
            }

            if (empty($follow_info)) {
                // 未授权登录
                session(['target_url' => $request->fullUrl()]);
                /*$auth_url = $request->mpApp->oauth->scopes(['snsapi_userinfo'])
                    ->redirect($request->domain() . url('Onmessage/wxAuth') .'?'. $request->queryString());
                */
                $auth_url = url('auth/authpage');
                //发起授权
                return $auth_url;
            }
            $request->followInfo = $follow_info;
            session([SESSION_MP_FOLLOW => $follow_info]); //保存用户信息
            View::assign('follow_info', $follow_info);
        }
        return $request;
    }

    private static function setTenantId(Request &$request)
    {
        if(! $tid = input('tenant', 0)){
            $tid = session(WECHAT_WAP_TENANTID);
        }
        if(empty($tid)){
            return  "页面访问非法";
        }
        session([WECHAT_WAP_TENANTID => $tid]);
        $request->tenantId = $tid;
        View::assign('tenant_id', $request->tenantId);
        return $request;
    }
}